local UIBase = require("view.UIBase")
local PopupChooseHero = class("PopupChooseHero", UIBase)
local ChooseHeroCell = require("view.hero.ChooseHeroCell")

local MAX_CELL = 5

function PopupChooseHero:ctor(callback)
    self._callback = callback
    local resource = {
        path = "Prefabs/Popup",
        name = "PopupChooseHero",
        canvas = 3
    }
    PopupChooseHero.super.ctor(self, resource)
end

function PopupChooseHero:start()
    self._selectedHeroId = 0
    self._btnOk.onClick:AddListener(handler(self, self._onBtnOkClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloceClikc))
    self._listView:SetTemplate(
        handler(self, self._onItemUpdate),
        handler(self, self._onValueChange),
        handler(self, self._onItemTouch)
    )
    self._datas = G_UserData:getHero():getHeroListNoBattle()
    local count = math.ceil(#self._datas / MAX_CELL)
    self._listView:ReSize(count)
end

function PopupChooseHero:onDestroy()
end

function PopupChooseHero:_onItemUpdate(item, index)
    local startIndex = index * MAX_CELL + 1
    local endIndex = startIndex + MAX_CELL - 1
    local lines = {}
    for i = startIndex, endIndex do
        local data = self._datas[i]
        if data then
            table.insert(lines, data)
        end
    end
    item:updateUI(lines, self._selectedHeroId)
end

function PopupChooseHero:_onValueChange()
end

function PopupChooseHero:_onItemTouch(heroId)
    self._selectedHeroId = heroId
    self._listView:UpdateUsedCell()
end

function PopupChooseHero:_onBtnOkClick()
    if self._callback then
        self._callback(self._selectedHeroId)
    end
    self:close()
end

function PopupChooseHero:_onBtnCloceClikc()
    self:close()
end

return PopupChooseHero
